package com.ldfile.server.exception;


import com.ldfile.server.response.SimpleResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO: 全局异常处理
 *
 * @author tao you sheng
 * @since 2020/7/21 11:20
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionResolver {

    /**
     * 参数异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public SimpleResponse validationErrorHandler(ConstraintViolationException ex) {
        List<String> errorInformation = ex.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        String message = errorInformation.toString().substring(1, errorInformation.toString().length() - 1);
        return SimpleResponse.fail(message, HttpStatus.NOT_IMPLEMENTED.value());
    }

    /**
     * FileServerException
     */
    @ExceptionHandler(FileServerException.class)
    public SimpleResponse fileServerExceptionHandler(FileServerException e) {
        return SimpleResponse.fail(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value());
    }

    /**
     * FileSizeLimitExceededException
     */


    /**
     * FileNotFoundException
     */
    @ExceptionHandler(FileNotFoundException.class)
    public SimpleResponse fileNotFoundExceptionHandler(FileNotFoundException e) {
        return SimpleResponse.fail("上传文件过大！", HttpStatus.INTERNAL_SERVER_ERROR.value());
    }
}
